<?php
/**
 * Benchmark
 *
 * @author tom.wang<tom.wang.sz@qq.com>
 */
class BenchmarkUtil {
	private static $tags;
	private static $markKeys = array('line', 'file', 'timestamp', 'memory');
	
	/**
	 * mark a tag
	 *
	 * @param string $tagName
	 * @return void
	 */
	public static function mark($tagName) {
		if(null !== self::$tags[$tagName]) {
			$markInfo = self::markInfo($tagName);
			throw new CatException("{$tagName} has register at file: {$markInfo['file']}, line: {$markInfo['line']}");
		}
		$trace = debug_backtrace();
		$infoArr = array_shift($trace);
		$infoArr['timestamp'] = microtime(true);
		$infoArr['memory'] = memory_get_usage(); //bytes
		
		$markArr = array();
		foreach(self::$markKeys as $markKey) {
			$markArr[$markKey] = null === $infoArr[$markKey] ? '' : $infoArr[$markKey];
		}
		
		self::$tags[$tagName] = $markArr;
	}
	
	/**
	 * get a mark's information
	 *
	 * @param string $tagName
	 * @return array
	 */
	public static function markInfo($tagName) {
		return self::$tags[$tagName];
	}
	
	/**
	 * dump all marks
	 *
	 * @return array
	 */
	public static function dump() {
		return self::$tags;
	}
	
	/**
	 * get timespan between two mark
	 * 
	 * @param string $tagName1
	 * @param string $tagName2
	 * @return float
	 */
	public static function diff($tagName1, $tagName2) {
		$noArr = array();
		if(null === self::$tags[$tagName1]) $noArr[] = $tagName1;
		if(null === self::$tags[$tagName2]) $noArr[] = $tagName2;
		
		if(array() !== $noArr) {
			throw new CatException(implode(',', $noArr) . " unregistered");
		}
		
		$timestamp_span = self::$tags[$tagName1]['timestamp'] - self::$tags[$tagName2]['timestamp'];
		$memory_span = self::$tags[$tagName1]['memory'] - self::$tags[$tagName2]['memory'];
		return array(
			abs($timestamp_span),
			abs($memory_span),
		);
	}
}
?>